

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/resource/img/favicon.png">
  <link rel="icon" type="image/png" href="/resource/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="soldier">
  <meta name="keywords" content="">
  <title>CAS你知道吗？ - 黄结的个人博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
    
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>soldier</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" href="/about/">
                    
                    个人简历
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://soldiergit.github.io/honor/">
                    
                    项目及获奖
                  </a>
                
              </div>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-11-10 10:49" pubdate>
        2020年11月10日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.6k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      20
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">CAS你知道吗？</h1>
            
            <div class="markdown-body" id="post-body">
              <h2 id="CAS-代码演示"><a href="#CAS-代码演示" class="headerlink" title="CAS 代码演示"></a>CAS 代码演示</h2><p>CAS： <strong><em><font color=#FF000>比较并交换</font></em></strong>，需要用到 JUC 的 Atomic 包下面的类来进行操作。</p>
<pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
    AtomicInteger atomicInteger = <span class="hljs-keyword">new</span> AtomicInteger(<span class="hljs-number">5</span>);

    <span class="hljs-comment">// main thread do thing...</span>

    <span class="hljs-comment">// 两个参数：int expect, int update，如果atomicInteger的当前值expect == 5，那么就将atomicInteger的值改为update</span>
    <span class="hljs-comment">// 如果线程的期望值跟主物理内存的真实值一样，那么就修改为线程的更新值，本次修改成功并返回true</span>
    System.out.println(atomicInteger.compareAndSet(<span class="hljs-number">5</span>, <span class="hljs-number">2019</span>) + <span class="hljs-string">&quot;\t current data:&quot;</span> + atomicInteger.get());

    <span class="hljs-comment">// 本次修改失败并返回false</span>
    System.out.println(atomicInteger.compareAndSet(<span class="hljs-number">5</span>, <span class="hljs-number">1024</span>) + <span class="hljs-string">&quot;\t current data:&quot;</span> + atomicInteger.get());
&#125;</code></pre>
<p>以上代码输出：</p>
<pre><code class="hljs text">true	 current data:2019
false	 current data:2019</code></pre>

<h2 id="CAS-底层原理？谈谈你对-UnSafe-的理解"><a href="#CAS-底层原理？谈谈你对-UnSafe-的理解" class="headerlink" title="CAS 底层原理？谈谈你对 UnSafe 的理解"></a>CAS 底层原理？谈谈你对 UnSafe 的理解</h2><p>自旋锁、UnSafe类</p>
<h3 id="以atomicInteger-getAndIncrement-为例"><a href="#以atomicInteger-getAndIncrement-为例" class="headerlink" title="以atomicInteger.getAndIncrement() 为例"></a>以atomicInteger.getAndIncrement() 为例</h3><p>在之前讲volatile时，我们使用 <strong>atomicInteger.getAndIncrement();</strong> 解决了 <strong>number++;</strong> 在多线程环境下的线程安全问题，它的底层源码实现为：</p>
<pre><code class="hljs java"><span class="hljs-comment">/**</span>
<span class="hljs-comment"> * Atomically increments by one the current value.</span>
<span class="hljs-comment"> *</span>
<span class="hljs-comment"> * <span class="hljs-doctag">@return</span> the previous value</span>
<span class="hljs-comment"> */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAndIncrement</span><span class="hljs-params">()</span> </span>&#123;
    <span class="hljs-keyword">return</span> unsafe.getAndAddInt(<span class="hljs-keyword">this</span>, valueOffset, <span class="hljs-number">1</span>);
&#125;</code></pre>
<p>该方法中， <strong>this</strong> 指的是当前对象， <strong>valueOffset</strong> 指的是当前对象的内存偏移量（就是内存地址）</p>
<h3 id="UnSafe"><a href="#UnSafe" class="headerlink" title="UnSafe"></a>UnSafe</h3><p><img src="/resource/img/java/UnSafe.png" srcset="/img/loading.gif"></p>
<ol>
<li><strong><em><font color=#FF000>UnSafe</font></em></strong> 是CAS的核心类，由于Java无法直接访问底层系统，需要通过本地（native）方法来访问，UnSafe相当于是一个后门，基于该类可以直接操作特定内存的数据。<font color=#FF000>UnSafe类存在于sun.misc包中</font>（存在于rt.jar，JDK从娘胎里就携带的最基础类），其内部方法操作可以想C的指针一样直接操作内存，因为Java中CAS操作执行依赖于UnSafe类的方法。<br><font color=#FF000><u><em>注意 UnSafe 类中所有方法都是native修饰的，也就是说UnSafe类中的方法都直接调用操作系统底层资源执行相应任务</em></u></font></li>
<li>变量<strong>valueOffset</strong> ，表示该变量值子啊内存中的<font color=#FF000>偏移地址</font>，因为UnSafe就是根据内存偏移地址获取数据的。<br><img src="/resource/img/java/valueOffset.png" srcset="/img/loading.gif"></li>
<li>变量 value 用 volatile 修饰，保证了多线程中间的内存可见性。</li>
</ol>
<h2 id="CAS是什么？"><a href="#CAS是什么？" class="headerlink" title="CAS是什么？"></a>CAS是什么？</h2><p><strong>CAS</strong>的全称为<strong>Compare-And-Swap</strong>，<font color=#FF000>它是一条<strong>CPU</strong>并发原语</font>。<br>它的功能是判断内存某个位置的值是否为预期值，如果是则更改为新的值，这个过程是原子的。（一致性）</p>
<p><strong>CAS</strong>并发原语体现在<strong>Java</strong>语言中就是<strong>sun.misc.UnSafe</strong>类中的各个方法。调用<strong>UnSafe</strong>类中的<strong>CAS</strong>方法，JVM会帮我们实现出<font color=#8A2BE2><strong>CAS汇编指令</strong></font>。这是6一种完全依赖于<font color=#FF000>硬件</font>的功能，通过它实现了原子操作。<br>再次强调，由于CAS是一种系统原语，原语属于操作系统用语范畴，是由若干条指令组成的，用于完成某个功能的一个过程，<font color=#FF000>并且原语的执行必须是连续的，在执行过程中不允许被中断，也就是说CAS是一条CPU的原子指令，不会造成所谓的数据不一致问题。</font><br><img src="/resource/img/java/CAS.png" srcset="/img/loading.gif"></p>
<pre><code class="hljs text">根据当前对象和当前对象的内存偏移量获取var5
判断刚刚获取的var5是不是等于对象本身的值，相等的话，加上var4
不相等的话 do while 继续，直到相等为止</code></pre>

<h3 id="unsafe-getAndAddInt"><a href="#unsafe-getAndAddInt" class="headerlink" title="unsafe.getAndAddInt();"></a>unsafe.getAndAddInt();</h3><p>var1 AtomicInteger对象本身。<br>var2 该对象值的引用地址。<br>var4 需要变动的数量。<br>var5 需要通过var1 var2 找出的主内存中真实存在的值，<br>用该对象当前的值与var5比较；<br>如果相同，更新var5+var4 并返回true，<br>如果不同，继续取值然后再比较，直到更新完成。<br><img src="/resource/img/java/unsafe-getAndAddInt.png" srcset="/img/loading.gif"><br>假设线程A和线程B两个线程同时执行getAndAddInt操作（分别跑在不同CPU上）：</p>
<ol>
<li>AtomicInteger里面的value原始值是5，即主内存中AtomicInteger的value为5，根据JMM模型，线程A和线程B各自持有一份值为5的value的副本分别到各自的工作内存；</li>
<li>线程A通过getIntVolatile(var1, var2)拿到value值为5，这是线程A被挂起；</li>
<li>线程B也通过getIntVolatile(var1, var2)方法获取到value值为5，此时刚好线程B<font color=#FF000>没有被挂起</font>并执行compareAndSwapInt方法比较内存值也为5，成功修改主内存值为6，线程B打完收工，一切OK；</li>
<li>这是线程A恢复，执行compareAndSwapInt方法比较，发现自己手里的值数字5和主内存的值数字6不一致，说明该值已经被其它线程抢先一步修改过了，那A线程本次修改失败，<font color=#FF000>只能重新读取重新来一遍了</font>；</li>
<li>线程A重新获取value值，因为变量value被volatile修饰，所以其它线程对它的修改，线程A总是能够看到，线程A继续执行compareAndSwapInt方法进行比较替换，直到成功。</li>
</ol>
<h3 id="底层汇编"><a href="#底层汇编" class="headerlink" title="底层汇编"></a>底层汇编</h3><p>UnSafe类中的compareAndSwapInt，是一个本地方法，该方法的实现位于unsafe.cpp中</p>
<pre><code class="hljs cpp">UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x))
  UnsafeWrapper(<span class="hljs-string">&quot;Unsafe_CompareAndSwapInt&quot;</span>);
  oop p = JNIHandles::resolve(obj);
  jint* addr = (jint *) index_oop_from_field_offset_long(p, offset);
  <span class="hljs-keyword">return</span> (jint)(Atomic::cmpxchg(x, addr, e)) == e;
UNSAFE_END</code></pre>
<p><font color=#FF000>(Atomic::cmpxchg(x, addr, e)) == e;</font>使得操作不用加synchronized也能保证原子性；<br><font color=#0000F><br>先想办法拿到变量value在内存中的地址；<br>通过Atomic::cmpxchg实现比较替换，其中参数x是即将更新的值，参数e是原内存的值。<br></font></p>
<h2 id="CAS的缺点"><a href="#CAS的缺点" class="headerlink" title="CAS的缺点"></a>CAS的缺点</h2><p><strong>1. 循环时间长开销很大</strong><br>我们可以看到getAndAddInt方法执行时，有个do while</p>
<pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAndAddInt</span><span class="hljs-params">(Object var1, <span class="hljs-keyword">long</span> var2, <span class="hljs-keyword">int</span> var4)</span> </span>&#123;
    <span class="hljs-keyword">int</span> var5;
    <span class="hljs-keyword">do</span> &#123;
        var5 = <span class="hljs-keyword">this</span>.getIntVolatile(var1, var2);
    &#125; <span class="hljs-keyword">while</span>(!<span class="hljs-keyword">this</span>.compareAndSwapInt(var1, var2, var5, var5 + var4));
    <span class="hljs-keyword">return</span> var5;
&#125;</code></pre>
<p>如果CAS失败，会一直进行尝试。如果CAS长时间一直不成功，可能会给CPU带来很大的开销。<br><strong>2. 只能保证一个共享变量的原子操作</strong><br><strong>3. 引出来ABA问题</strong></p>
<h2 id="CAS-手写实现"><a href="#CAS-手写实现" class="headerlink" title="CAS 手写实现"></a>CAS 手写实现</h2><p>CAS 是采用 JNI(Java Native Interface) 的底层方法实现的，调用 c语言 来执行 cpu 的指令,而 cpu 则执行指令”cmpchg”执行来进行比较替换的操作，这是一个原子性的操作。</p>
<pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CompareAndSwap</span> </span>&#123;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * cas 原则: 原值 = 预期值 的情况下更新  新值</span>
<span class="hljs-comment">     *</span>
<span class="hljs-comment">     * 原值: count当前的值</span>
<span class="hljs-comment">     * 预期值: count最新的值</span>
<span class="hljs-comment">     * 新值: 需要更新的值</span>
<span class="hljs-comment">     */</span>

    <span class="hljs-comment">// 使用volatile保证可见性，实时获取count的值</span>
    <span class="hljs-keyword">volatile</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> count = <span class="hljs-number">0</span>;

    <span class="hljs-comment">// 实现方法</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">request</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-keyword">int</span> oldValue = getCount();
        <span class="hljs-keyword">if</span> (!compareAndSwap(oldValue,oldValue + <span class="hljs-number">1</span>))&#123;

        &#125;
    &#125;

    <span class="hljs-comment">// 比较原值和预期值</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">compareAndSwap</span><span class="hljs-params">(<span class="hljs-keyword">int</span> oldValue,<span class="hljs-keyword">int</span> newValue)</span></span>&#123;
        <span class="hljs-keyword">if</span> (getCount() == oldValue) &#123;
            count = newValue;
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
        &#125;
        <span class="hljs-keyword">else</span>&#123;
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
        &#125;
    &#125;

    <span class="hljs-comment">// 获取count值</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getCount</span><span class="hljs-params">()</span></span>&#123;
        <span class="hljs-keyword">return</span> count;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) &#123;
            Thread thread = <span class="hljs-keyword">new</span> Thread(CompareAndSwap::request);
            thread.start();
        &#125;
        System.out.println(count);
    &#125;
&#125;</code></pre>


            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E9%9D%A2%E8%AF%95%E9%A2%98/">面试题</a>
                    
                      <a class="hover-with-bg" href="/tags/Java%E9%9D%A2%E8%AF%95%E9%A2%98/">Java面试题</a>
                    
                      <a class="hover-with-bg" href="/tags/CAS/">CAS</a>
                    
                      <a class="hover-with-bg" href="/tags/UnSafe/">UnSafe</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/11/15/java/ABA/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">原子类AtomicInteger的ABA问题谈谈？原子更新引用知道吗？</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/11/03/java/volatile/">
                        <span class="hidden-mobile">请谈谈你对volatile的理解</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://soldiergit.github.io/" target="_blank" rel="nofollow noopener"><span>Copyright © 2020 soldier Powered by Hexo Fluid Core on Kubernetes</span></a> <i class="iconfont icon-love"></i> <a href="mailto:soldier_wyyx@163.com"><span>联系我</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "CAS你知道吗？&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>












  
    <!-- Baidu Analytics -->
    <script defer>
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?28d1b3a306f2b9f13ed66ffd0d5a0a9a";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  

  

  
    <!-- Tencent Analytics -->
    <script defer>
      var _mtac = {};
      (function () {
        var mta = document.createElement("script");
        mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
        mta.setAttribute("name", "MTAH5");
        mta.setAttribute("sid", "500732630");
        
        mta.setAttribute("cid", "500732632");
        
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(mta, s);
      })();
    </script>
  

  
    <!-- 51.la Analytics -->
    <script defer type="text/javascript" src="//js.users.51.la/20973747.js"></script>
  

  





</body>
</html>
